<template>
  <a-card>
    <div class="card-header">
      <a-space>
        <span class="card-header-title">角色管理</span>
        <a-tag>{{data.length||0}}</a-tag>
      </a-space>
      <role-modal @ok="createOk" v-model:open="open" v-model:id="editorId"/>
    </div>
    <a-alert message="角色有上限，请合理安排" class="margin-bottom" banner/>
    <a-table
        :columns="columns"
        :data-source="data"
        :pagination="tablePageConfig"
        :loading="state.loading"
        :row-key="record => record.id"
        :row-selection="{
        selectedRowKeys: state.selectedRowKeys,
        onChange: onSelectChange,
      }"
    >
      <template #bodyCell="{column,record}">
        <template v-if="column.dataIndex === 'role_name'">
          <a-tag :color="record.style">{{record.role_name}}</a-tag>
          <div class="color-gray padding-top-sm">{{record.description}}</div>
        </template>
        <template v-else-if="column.dataIndex === 'status'">
          <a-tag :color="record.status?'green':''">{{record.status ? '已启用' : '已禁用'}}</a-tag>
        </template>
        <template v-else-if="column.key === 'action'">
          <span class="table-action" v-if="record.enterprise_id">
            <span @click="handleEdit(record.id)">编辑</span>
            <span @click="handleDelete(record.id)">删除</span>
          </span>
          <span v-else class="color-gray">内置规则无法修改</span>
        </template>
      </template>
    </a-table>
  </a-card>

</template>
<script setup lang="ts">
import {tablePageConfig} from "@/config";
import {onMounted, reactive, ref} from "vue";
import RoleModal from "@/views/admin/components/RoleModal.vue";
import {roleList, roleDelete} from "@/api/modules/permission";
import {Modal} from 'ant-design-vue'
import useMessage from "@/plugin/useMessage";

const data = ref<UserItem[]>([])
const open = ref<boolean>(false),editorId = ref<number>(0)
const columns = [
  {title: '角色名称', dataIndex: 'role_name', key: 'role_name'},
  {title: '状态', dataIndex: 'status', key: 'status',width:100},
  {title: '管理', key: 'action',width: 200,},
]
const state = reactive({
  loading: false,
  selectedRowKeys: [],
})
const getDataList = async () => {
  state.loading = true
  const res = await roleList()
  if(res.code === 200){
    data.value = res.data
  }
  state.loading = false
}
onMounted(()=>{
  getDataList()
})
const onSelectChange = (selectedRowKeys: string[]) => {
  selectedRowKeys.value = selected
}
const createOk = () => {
  setTimeout(() => {getDataList()},500)
}
const handleDelete = (id:number) => {
  Modal.confirm({
    title: '确认删除该角色吗？',
    content: '删除后无法恢复',
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      const res = await roleDelete(id)
      if(res.code === 200){
        await getDataList()
      }
      useMessage(res.code,res.message)
    }
  })
}
const handleEdit = (id:number) => {
  open.value = true
  editorId.value = id
}
</script>

<style scoped>

</style>